package xj.toolkit.netty.handler.codec.http.ssl;

import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

public class HttpSslContextFactory implements InitializingBean {

	private boolean useSsl;

	private Resource keyStoreResource = null;

	private String keyPassword = null;

	public Resource getKeyStoreResource() {
		return keyStoreResource;
	}

	public void setKeyStoreResource(Resource keyStoreResource) {
		this.keyStoreResource = keyStoreResource;
	}

	public String getKeyPassword() {
		return keyPassword;
	}

	public void setKeyPassword(String keyPassword) {
		this.keyPassword = keyPassword;
	}

	private SslContext serverSslContext = null;

	private SslContext clientSslContext = null;

	/**
	 * @return the useSsl
	 */
	public boolean isUseSsl() {
		return useSsl;
	}

	/**
	 * @param useSsl
	 *            the useSsl to set
	 */
	public void setUseSsl(boolean useSsl) {
		this.useSsl = useSsl;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (!useSsl) {
			return;
		}

		if (getKeyStoreResource() == null || !getKeyStoreResource().exists()) {
			throw new Exception("Pls set keystore file.");
		}

		if (StringUtils.isBlank(getKeyPassword())) {
			throw new Exception("Pls set password.");
		}

		KeyStore keyStore = KeyStore.getInstance("JKS");
		keyStore.load(getKeyStoreResource().getInputStream(), getKeyPassword().toCharArray());
		KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
		keyManagerFactory.init(keyStore, getKeyPassword().toCharArray());
		serverSslContext = SslContextBuilder.forServer(keyManagerFactory).build();
		clientSslContext = SslContextBuilder.forClient().build();
	}

	public SslContext getServerSslContext() {
		return serverSslContext;
	}

	public SslContext getClientSslContext() {
		return clientSslContext;
	}
}
